import { RootThunkAction } from "@/types/store";
import { http } from "../../utils/http";
import { clearToken, setToken } from "../../utils/token";
import type { Token, LoginResponse } from "@/types/data";

// login 函数的参数类型
type LoginParams = { mobile: string; code: string };
// login 接口的响应类型

export const login = (values: LoginParams): RootThunkAction => {
  return async (dispatch) => {
    // 发送请求
    const res = await http.post<LoginResponse>("/authorizations", values);
    // 拿到返回数据
    const tokens = res.data.data;
    // 设置本地token
    setToken(tokens);
    // 分发 action 将 token 保存到 redux state 中
    dispatch({ type: "login/token", payload: tokens });
  };
};
// 获取验证码
export const getCode = (mobile: string) => {
  return async () => {
    await http.get(`/sms/codes/${mobile}`);

    // 注意：验证码是发送到手机上的，因此，不需要更新Redux状态
  };
};
export const logout = (): RootThunkAction => {
  return async (dispatch) => {
    dispatch({ type: "login/logout" });
    clearToken();
  };
};
